<template>
  <div>
    <basic-container>
      <div class="boxsty zhiBiao">
        <div :height="searchheight">
          <span
            style="float: right; margin-top: -30px; cursor: pointer"
            @click="searchchangeadvanced"
            >{{ searchadvanced ? "查询条件收起" : "查询条件展开" }}
            <i
              :class="
                searchadvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "
            />
          </span>
          <el-row v-show="searchadvanced">
            <el-col :span="24">
              <el-form
                :inline="true"
                :model="dataForm"
                @keyup.enter.native="getDataList()"
                class="form-inline"
                label-width="100px"
              >
              <!-- <el-col :span="6">
                  <el-form-item label="奖金类型">
                    <el-select
                      v-model="dataForm.jjLx"
                      placeholder="请选择"
                      :clearable="true"
                      style="width: 100%"
                    >
                      <el-option value="1" label="年度"></el-option>
                      <el-option value="3" label="日常"></el-option>
                    </el-select>
                </el-form-item>
              </el-col> 
                <el-col :span="6" v-if="dataForm.jjLx == 1">
                  <el-form-item label="年份">
                    <el-date-picker
                      value-format="yyyy"
                      :picker-options="pickerOptions0"
                      :clearable="true"
                      v-model="dataForm.fpYear"
                      type="year"
                      placeholder="选择年"
                      style="width: 100%"
                    >
                    </el-date-picker>
                </el-form-item>
                </el-col>
                <el-col :span="6" v-if="dataForm.jjLx == 3">
                  <el-form-item label="月份">
                    <div
                      class="el-date-editor el-range-editor el-input__inner"
                      style="width: 240px"
                    >
                      <el-select
                        size="mini"
                        v-model="dataForm.startMonth"
                        style="width: 90px"
                        placeholder=""
                      >
                        <el-option
                          v-for="item in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)"
                          :key="item"
                          :value="item"
                          :label="item + '月'"
                          :clearable="true"
                        ></el-option>
                      </el-select>
                      <slot name="range-separator">
                        <span style="width: 40px" class="el-range-separator"
                        >至</span
                        >
                      </slot>
                      <el-select
                        size="mini"
                        v-model="dataForm.endMonth"
                        style="width: 90px"
                        placeholder=""
                      >
                        <el-option
                          v-for="item in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)"
                          :key="item"
                          :value="item"
                          :clearable="true"
                          :label="item + '月'"
                        ></el-option>
                      </el-select>
                    </div>
                  </el-form-item>
                </el-col>-->
                <el-col :span="6">
                  <el-form-item label="开始日期">
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      :clearable="true"
                      v-model="dataForm.startDate"
                      type="date"
                      placeholder="选择开始日期"
                      style="width: 95%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="结束日期">
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      :clearable="true"
                      v-model="dataForm.endDate"
                      type="date"
                      placeholder="选择结束日期"
                      style="width: 95%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="奖金项">
                    <el-select
                      v-model="dataForm.jjxId"
                      placeholder="选择奖金项"
                      clearable
                      class="xiaLa"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in jjxOptions"
                        :key="index"
                        :label="item.jjxMc"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item> 
                </el-col>
                <!-- <el-col :span="6">
                  <el-form-item label="奖金名称">
                  <el-input
                    v-model="dataForm.fpName"
                    placeholder="奖金名称"
                    :clearable="true"
                  ></el-input>
                </el-form-item>
                </el-col> -->
                <el-col :span="6">
                  <el-form-item label="机构名称">
                    <el-cascader
                      v-model="departmentSelect"
                      :options="departmentOptions"
                      :props="{
                        multiple: true,
                        checkStrictly: true,
                        expandTrigger: 'hover',
                        value: 'id',
                        label: 'name',
                      }"
                      clearable
                    ></el-cascader>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                  <el-form-item label="员工子组">
                    <el-select
                      :clearable="true"
                      v-model="dataForm.ryZz"
                      placeholder="请选择"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in userZzOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :span="6">
                  <el-form-item label="岗位层级">
                    <el-select
                      :clearable="true"
                      v-model="dataForm.ryZwjb"
                      placeholder="请选择"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in userZjOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="职务">
                    <el-input
                      :clearable="true"
                      v-model="dataForm.ryZhiwei"
                      placeholder="职务"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="人员姓名">
                    <el-input
                      :clearable="true"
                      v-model="dataForm.ryName"
                      placeholder="人员姓名"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item> 
                </el-col>
                <el-col :span="6">
                  <el-form-item label="人员编号">
                    <el-input
                      :clearable="true"
                      v-model="dataForm.ryCode"
                      placeholder="人员编号"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item>
                  <el-button
                    type="primary"
                    class="marginLeft"
                    plain
                    @click="getDataList(1)"
                    >检索</el-button
                  >
                  <el-button
                    type="warning"
                    class="marginLeft"
                   plain
                    @click="upEcc"
                    >上传ECC</el-button
                  >
                  <el-button
                    type="primary"
                    class="marginLeft"
                    plain
                    @click="downLoad"
                    >导出</el-button
                  >
                  <el-button
                    type="primary"
                    class="marginLeft"
                    plain
                    @click="configurationBtn"
                    >配置</el-button
                  >
                </el-form-item>
                </el-col>
                
              </el-form>
            </el-col>
          </el-row>
        </div>
        <el-table
          :data="tableData"
          ref="multipleTable"
          border
          v-loading="loading"
          max-height="600"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            prop=""
            label="序号"
            min-width="60"
            :formatter="nShowIndex"
            align="center"
            fixed="left"
          ></el-table-column>
          <el-table-column
            v-for="(item,colIndex) in tableColumn"
            :label="item.label"
            :key="colIndex"
            min-width="120"
            :fixed="colIndex<5?'left':false"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row[item.prop] }}</span>
            </template>
            <el-table-column
              v-if="item.children"
              v-for="(it,key) in item.children"
              :label="it.label"
              :key="key"
            >
              <template slot-scope="scope">
                <span>{{ scope.row[it.prop] }}</span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      <el-dialog
        title="配置"
        :visible.sync="configDialogVisible"
        width="60%"
        :close-on-click-modal="false"
        v-loading="configLoading"
        center>
        <div>
          <el-col :span="24" style="margin-bottom:10px;">
            <span>批量填写日期:</span>
            <el-date-picker
                v-model="riQi"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyyMMdd"
                @change="changeDate"
                placeholder="选择日期">
              </el-date-picker>
          </el-col>
          <el-table
          :data="configTableData"
          align="center"
          max-height="500"
          style="width: 100%">
          <el-table-column
            prop="jjx_mc"
            label="奖金项名称"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            prop="rq"
            label="日期"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.rq"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyyMMdd"
                placeholder="选择日期">
              </el-date-picker>
             
            </template>
          </el-table-column>
          <el-table-column
            prop="request_type"
            label="发放类型"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <el-switch
              v-model="scope.row.request_type"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="单独发放"
              inactive-text="偶然性发放"
              @change="changeSwitch(scope.row)"
              active-value="performanceBonusSeparate"
              inactive-value="performanceBonusAccidental">
              </el-switch>
              
            </template>
          </el-table-column>
          <el-table-column
            prop="aperiodic_cause"
            label="非周期原因"
            align="center"
            width="180">
            <template slot-scope="scope">
               <el-select
                      :clearable="true"
                      v-if="scope.row.request_type=='performanceBonusSeparate'" 
                      v-model="scope.row.aperiodic_cause"
                      placeholder="请选择"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in requestOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
               </el-select>
              
            </template>
          </el-table-column>
        </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="configDialogVisible = false">取 消</el-button>
          <el-button type="primary" v-if="!isEcc" @click="isKong('保存')">保存</el-button>
          <el-button type="primary" v-if="isEcc" @click="submintEcc(configTableData)">提交</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchTree } from "@/api/admin/dept";
import { updateGrFP } from "@/api/jiangjin/jiangjinjjxxxb";
import { getJjDeptJjx,
         exportExcelRenyuanList,
         getUserDeptId,
         getUserDeptInfo,
         getSetting,
         setting,
         uploadEcc
 } from "@/api/jiangjin/jiangjinjjxxxb";
import { remote as remoteDict } from "@/api/admin/dict";
import { perselectResultPage } from "@/api/jiangjin/jiangjinfpjjbmfppzmxb";
export default {
  data() {
    return {
      innerVisible: true,
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      tableColumn: [],
      loading: false,
      dataForm: {},
      departmentOptions: [],
      jjxOptions: [],
      deptId: "1",
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;
        },
      },
      userZjOptions: [], // 职级
      userZzOptions: [], // 人员子组
      searchadvanced: true,
      searchheight: "0",
      departmentSelect:[],
      configTableData:[],
      configDialogVisible:false,
      jjxId:"",
      requestOptions:[
        {label:"9000奖金-单独发放",value:"9000"},
        {label:"9001过节费-单独发放",value:"9001"},
        {label:"9003津补贴-单独发放",value:"9003"},
        {label:"9004补发岗位工资-单独发放",value:"9004"},
      ],
      riQi:"",
      isEcc:false,
      configLoading:false
    };
  },
  created() {
   
    // 获取人员职级代码
    remoteDict("user_zj").then((response) => {
      this.userZjOptions = response.data.data;
    });
    // 获取员工子组代码
    remoteDict("subgroup").then((response) => {
      this.userZzOptions = response.data.data;
    });
   // this.$set(this.dataForm,'jjLx','3')
    
    this.ongetUserDeptId()
  },
  methods: {
    changeSwitch(row){
      if(row.request_type=='performanceBonusAccidental'){
        row.aperiodic_cause=""
      }
    },
    upEcc(){
        this.$confirm('是否使用已有配置?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.submintEcc([])
        }).catch(() => {
             this.configurationBtn('ecc')     
        });
    },
    submintEcc(data){
      var params={
        'datas':data
      }
      if(data.length==0){
        this.onuploadEcc(params)
      }else{
        this.isKong('ecc')
      }
     
    },
    onuploadEcc(params){
      params.dataForm = this.dataForm
      uploadEcc(params).then(res=>{
        if(res.data.data){
          this.$message.closeAll()
          this.$message.success('提交成功!')
          this.configDialogVisible=false
          this.getDataList()
          //this.ongetSetting()
        }else{
          this.$message.closeAll()
          this.$message.error('提交失败!')
        }
      })
    },
    changeDate(){
      this.configTableData.forEach(item=>{
        this.$set(item,'rq',this.riQi)
      })
      this.$forceUpdate()
    },
    async xunahun(){
      
    },
    isKong(type){
      var list=[],obj={}
     // debugger
      var errorRet = false;
      for(var i = 0;i<this.configTableData.length;++i){
        var item = this.configTableData[i];
        console.log(JSON.stringify(item))
         if(item.rq==''){
          this.$message.closeAll()
          this.$message.warning('日期不能为空')
          errorRet = true;
          break
        }
        //request_type
        if(item.request_type==''){
          this.$message.closeAll()
          this.$message.warning('发放类型不能为空')
          errorRet = true;
          break
        }
        if(item.request_type=='performanceBonusSeparate'){
          if(item.aperiodic_cause==''){
            this.$message.closeAll()
            this.$message.warning('非周期原因不能为空')
            errorRet = true;
            break
          }
        }
        obj={
            jjxId:item.jjx_id,
            rq:item.rq,
            type:item.request_type,
            aperiodicCause:item.aperiodic_cause
          }
          list.push(obj)
      }
      if(errorRet)
        return
      var params={
        datas:list
      }
      console.log(JSON.stringify(params))
     
      if(type=='保存'){
        this.keepRow(params)
      }
      if(type=='ecc'){
        this.onuploadEcc(params)
      }
    },
    keepRow(params){
      setting(params).then(res=>{
        if(res.data.data){
          this.$message.closeAll()
          this.$message.success('保存成功!')
         
          //this.ongetSetting()
        }else{
          this.$message.closeAll()
          this.$message.error('保存失败!')
        }
      })
    },
    //配置
    configurationBtn(type){
      this.configDialogVisible=true
      if(type=='ecc'){
        this.isEcc=true
      }else{
        this.isEcc=false
      }
      this.ongetSetting()
    },
    ongetSetting(){
      this.configLoading=true
      this.riQi=""
      getSetting().then(res=>{
        this.configTableData=res.data.data
        this.configLoading=false
      })
    },
    ongetUserDeptId(){
      getUserDeptId().then(res=>{
        if(res.data.data){
		  this.deptId = res.data.data
		  this.getJjDeptJjx();
          fetchTree({pid:res.data.data}).then((response) => {
            if(response.data.data.length>0){
               this.departmentOptions = this.dealTreeData(response.data.data);
            }else{
              getUserDeptInfo().then(res=>{
                this.departmentOptions=this.dealTreeData(res.data.data)
                
              })
            }
          });
        }
      })
    },
    // 处理部门tree数据，将最后的children:[]改成undefined,否则级联下拉框会多出一层
    dealTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.dealTreeData(data[i].children);
        }
      }
      return data;
    },
    downLoad(){
      this.dataForm.deptIds = ''
      if (this.departmentSelect.length > 0) {
        for (let i=0; i<this.departmentSelect.length; i++) {
          const dep = this.departmentSelect[i]
          this.dataForm.deptIds += dep[dep.length - 1] + ','
        }
        this.dataForm.deptIds = this.dataForm.deptIds.substring(0, this.dataForm.deptIds.length - 1)
      }
      exportExcelRenyuanList(Object.assign(
          {
            pageNum: this.pageIndex,
            pageSize: this.pageSize,
          },
          this.dataForm
        )).then(res=>{
        this.$message.closeAll();
          this.$message.success("下载成功!");
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "人员奖金导出.xls");
          document.body.appendChild(link);
          link.click();
      })
    },
    //检索
    getDataList(flag) {
      // 处理部门级联选择结果：[]->xx,xx
      this.dataForm.deptIds = ''
      if (this.departmentSelect.length > 0) {
        for (let i=0; i<this.departmentSelect.length; i++) {
          const dep = this.departmentSelect[i]
          this.dataForm.deptIds += dep[dep.length - 1] + ','
        }
        this.dataForm.deptIds = this.dataForm.deptIds.substring(0, this.dataForm.deptIds.length - 1)
      }
      this.loading = true;
      if(flag==1){
        this.pageIndex=1
      }
      perselectResultPage(
        Object.assign(
          {
            pageNum: this.pageIndex,
            pageSize: this.pageSize,
          },
          this.dataForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.tableData;
          this.totalPage = response.data.data.totalPage;
          this.loading = false;
          this.tableColumn = response.data.data.tableColumn;
          //this.csh()
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    csh(){
      this.dataForm={
          startDate:"",
          endDate:"",
          jjxId:"",
          deptIds:"",
          ryZwjb:"",
          ryZhiwei:"",
          ryName:"",
          ryCode:""
      }
    },
    init(fpId, cfLx, isfang) {
      this.getupdateBmFP(fpId, cfLx);
      this.isfang = isfang;
    },
    getupdateBmFP(fpId, cfLx) {
      this.loading = true;
      updateGrFP(fpId, cfLx).then((res) => {
        this.tableData = res.data.data.tableData;
        this.tableColumn = res.data.data.tableColumn;
        this.loading = false;
      });
    },
    //获取奖金项列表
    getJjDeptJjx() {
      getJjDeptJjx(this.deptId).then((res) => {
        this.jjxOptions = res.data.data;
      });
    },
    nShowIndex(row, column, cellValue, index) {
      return index + 1 + this.pageSize * (this.pageIndex - 1);
    },
    searchchangeadvanced() {
      this.searchadvanced = !this.searchadvanced;
      if (this.searchadvanced) {
        this.searchheight = "auto";
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
  },
};
</script>

<style>
.ffdi {
  padding: 5px 10px;
}
</style>
<style scoped>
.el-range-editor.el-input__inner{
  background: linear-gradient(45deg, #f4f4fc, #f5f5f5);
}

</style>